package com.hanliy.storage.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.hanliy.storage.StorageType;
import lombok.Data;

import java.io.InputStream;

/**
 * @author hanyulin
 * @apiNote
 * @date 2021/12/4 11:00
 */
@Data
public class AliyunStorageImpl implements StorageType {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 获取阿里云OSS客户端对象
     *
     * @return OSS
     * @author hanyulin
     * @date 2021/12/4 15:07
     */
    private OSS getOssClient() {
        //return new OSSClient(endpoint, accessKeyId, accessKeySecret);
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    private String getBaseUrl() {
        return "https://" + bucketName + "." + endpoint + "/";
    }

    @Override
    public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
        try {
            // 设置存储类型和访问权限
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(contentLength);
            objectMetadata.setContentType(contentType);
            // 上传的图片   key：对象键为folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, "testDir/" + keyName, inputStream, objectMetadata);
            // 上传文件。
            getOssClient().putObject(putObjectRequest);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            getOssClient().shutdown();
        }

    }

    @Override
    public String generateUrl(String keyName) {
        return getBaseUrl() + keyName;
    }

    @Override
    public void delete(String key) {
        try {
            getOssClient().deleteObject(bucketName, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
